I want to programatically set the input to invalid if specific condition is met e.g
<input type="text" required />
Lets take a variable isValid an example, if that is false, i want that bubble to show up with default browser bubble (onsubmit) and the custom error thats provided. So to add custom errors i figured the solition
<input
type="text"
required
oninvalid="this.setCustomValidity('Please Enter valid name')"
oninput="setCustomValidity('')"
/>
However this only check if its empty, the extra validation comes from a field called pattern however that regex, so I was thinking maybe do a pretty much all case regex when is 'isValid == true' else a regex that will fall everytime e.g. (react)
<input
type="text"
required
pattern={isValid ? 'regex valid always' : 'regex fail always'}
...
/>
Could this even work? is there a better way that I'm not seeing?
Thanks to #revo for his help got it working with just:
<input
type="text"
required
pattern={isValid ? null : '(?!)'}
...
/>
Related
Is there any way to validate inputs in the form using HMTL?
For example:
<input type="text" class="input-text error"
aria-required="true" placeholder="Enter your name *"
aria-invalid="true" required />
If user adds a special character to input, an error message saying "Characters are not allowed" should be shown below the input box.
First of all, client-side form validation is the greatest feature coming with the HTML5. Client-side form validation helps you to ensure data submitted matches the requirements. To get more detail about it you can visit here.
Important Note
Client-side form validation is an initial check, You should not use data coming from the form on the server side without checking it. It just a feature for good user experience. Because client-side validation is too easy to manipulate, so users can still easily send data that you do not want to on your server.
Solution
In this question, the best solution is; using HTML attribute pattern. The pattern attribute defines a regular expression the form control's value should match. To get more detail about pattern attribute you can visit the this page.
Below regexp you need.
^[a-zA-Z0-9]{5,12}$
It works like that;
It should contains only alphanumeric.
Minumum 5 and maximum 10
character.
You can use below code to integrate it with input field.
<form action="">
<input type="text" name="name" required
pattern="[a-zA-Z0-9]{5,12}" title="No special character">
<input type="submit">
</form>
Usually, to check inputs from html tags, you can create a javascript function to check your needs which is called everytime the user type in your input with the "onkeyup()" function.
The "onkeyup" keyword will trigger the function everytime user type in your field
<input type="text" onkeyup="myFunctionToCheck()">
<script>
myFunctionToCheck(){
//Here check your needs
}
</script>
I'm using the html5 input pattern attribute to check for a time in HH:MM AM or HH:MM PM format. The inout control is coded like this:
<input class="form-control input-sm" id="ConcertTime" name="ConcertStartTime" type="text" pattern="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\040(AM|am|PM|pm)$" title="hh:mm AM/PM" required placeholder="hh:mm AM/PM">
After keying in something which doesn't match the pattern and clicking the Submit button, no error is flagged. Other validation attributes (e.g. the "required" on this input) are correctly handled.
I've tried the regex in various regex test programs and it successfully detects valid and invalid time formats.
This is in Chrome 62.0.3202.94
Never mind. The js console reveals that html doesn't like the \040 in the regex, thinks it is an invalid sequence. Replaced it with a space character and all now works fine.
Please try this
<input type="time" name="time" />
I am currently doing homework, and following the instructions the book gives me, but I can't get the required or pattern tags to work. I am creating a survey form, and trying to make an error come up when the user doesn't type in their name, receipt number, or email. Here is a portion of it.
<label for"receipt">Receipt number *</label>
<input name="receipt" id="receipt"
placeholder="re-nnnnnn"
required="required"
pattern="^re\-\d{6}$" />
A few things i see
the required attribute does not need a value, the existence of the attribute is what makes it required or not.
the - does not need to be escaped so use ^re-\d{6}$ for the pattern attribute
the issue with the notepad++ is that the language formatting/color-coding is not up-to-date with all the attributes.
<input name="receipt" id="receipt"
placeholder="re-nnnnnn"
required pattern="^re-\d{6}$" />
there is no need to write like that u can just write : required and it will work
and whats your pattern i don't catch that
This little HTML5 password field works perfectly WITHOUT the oninvalid attribute (the pattern say: minimum 6 characters):
<form>
<input type="password" name="user_password_new" pattern=".{6,}" required />
<input type="submit" name="register" value="Register" />
</form>
See the jsFiddle here.
But when I add an oninvalid attribute that gives out a custom error message when user's input does not fit the pattern, the entire field NEVER becomes valid, see the code here:
<form>
<input type="password" name="user_password_new" pattern=".{6,}" oninvalid="setCustomValidity('Minimum length is 6 characters')" required />
<input type="submit" name="register" value="Register" />
</form>
See the jsFiddle here.
Can you spot the mistake ?
If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to allow for the effects of any other validations you have to clear the custom validity:
<input type="password" name="user_password_new" pattern=".{6,}" required
oninvalid="setCustomValidity('Minimum length is 6 characters')"
oninput="setCustomValidity('')" />
Since I stumbled on the same problem, here is my solution – tested and working with FF, Chrome, IE 10, Edge (Feb 2017).
<form>
<input pattern="1234" oninput="setCustomValidity(''); checkValidity(); setCustomValidity(validity.valid ? '' :'please enter 1234');">
<input type="email" required>
<input type="submit">
</form>
Explanation:
setCustomValidity(''); removes the custom error string which otherwise would always result in an invalid field at the validation process.
checkValidity(); does a manual validation – the same as it is happening at the form submisson. The result is stored in validity.valid.
The second setCustomValidity(validity.valid ? '' :'please enter 1234'); now sets the error string according to the validation result. If the field is valid it needs to be empty, otherwise the custom error string can be set.
I like to use like this:
<input type="email" name="Email" required oninvalid="setCustomValidity('ErrorMessage')"/>
And unplugged for all of valid input data
UPD, one more thing for better work:
$("input").attr("onblur", "setCustomValidity('')");
$("input").attr("oninput", "setCustomValidity(' ')");
Although the answers for this question had good information, they weren't sufficient for my needs. I need to display different messages depending on which validity rule failed. In the other examples, the same validation failure message is used for all valiation failures.
The "validity" property of a form object holds the key to creating more than one validation failure message.
You can review all of the different "validity" property properties at this web site.
https://www.w3schools.com/js/js_validation_api.asp
This example shows how to display two different validation messages. If you uncomment the console.log() line below you can watch the validity property change as you type in a field.
<label for="user_password_new">New Password:</label>
<input type="password" name="user_password_new" id="user_password_new"
pattern=".{6,}"
value=""
required
oninput="
setCustomValidity('');
checkValidity();
// console.log(validity);
if (validity.patternMismatch) {
setCustomValidity('Please enter at least six characters.');
}
else if (validity.valueMissing) {
setCustomValidity('This field is required.');
}
else if (validity.valid) {
setCustomValidity('');
}
// allow default validation message to appear for other validation failures
"
>
NOTE: Some validity checks are "type" specific. For example, the "rangeOverflow", "rangeUnderflow", and "stepMismatch" attributes get set if type uses them; type="number".
You can use title as long as you don't mind having 'You must use this format:' before your message. If you want a full custom message, the setCustomValidity() worked for me.
I have never seen this, have no idea what is going on:
<form action="/cgi-bin/Lib.exe" method=POST name="slider" ID="Form2">
<input type="text" name="user" value="" ID="Text1">
<input type="text" name="end" value="" ID="Text2">
</form>
function setval()
{
alert(s.getValue());
alert(s2.getValue());
document.slider.user.value = s.getValue();//set value of hidden text box to value of slider
document.slider.end.value = s2.getValue();//set value of hidden text box to value of slider
document.slider.submit();
}
When submitting form from setval(), when I change the name of the first input box from "user" to anything else, my cgi application won't except it and I get an error? I can change the name of the secons input box to anyting and it doesn't seem to have any problem? Confused. Thanks!
Seems more like it's a problem with the cgi than it is with the HTML/Javascript, to me. It probably makes the assumption that a value for "user" will always be sent. Not much else I can tell you without seeing the form-processing code.
Your CGI must be expecting an element called 'user'. You would need to check the source.