Why does this input pattern not work? - html

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" />

Related

Regex number pattern and maxlength not working on IE

Number pattern and max length are not working on IE.
I have tried variations of the below HTML, though IE appears to bypass that validation.
<input id="phone" maxlength="10" minlength="10" pattern="[0-9.]+" type="text">
Any suggestions on enforcing the above on IE?
The goal is to only allow 10-digits for that input field.
You can use an <input type="tel"> element, but it actually allows you to enter any characters. So, ultimately you need to specify a pattern and be very explicit as to what you are looking for and rely on HTML5 form validation. For example, if you are trying to input a phone number of the format 999.999.9999, then you want a something like the following. If you enter something that does not match the pattern and try to submit the form by hitting enter, you will get an error indication. Of course, use whatever pattern you want. If you just want digits and decimal points in any order (why?) but they must be length 10, then use pattern="[0-9.]{10}".
<form>
<input type="tel" pattern="[0-9]{3}\.[0-9]{3}\.[0-9]{4}" required>
</form>

Purposely invalidate the html5 form validator using dummy pattern

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 : '(?!)'}
...
/>

How to force only numbers in a input, without Javascript?

CodePen: http://codepen.io/leongaban/pen/hbHsk
I've found multiple answers to this question on stack here and here
However they all suggest the same fix, using type="number" or type="tel"
None of these are working in my codepen or project :(
Do you see what I'm missing?
Firstly, what browsers are you using? Not all browsers support the HTML5 input types, so if you need to support users who might use old browsers then you can't rely on the HTML5 input types working for all users.
Secondly the HTML5 input validation types aren't intended to do anything to stop you entering invalid values; they merely do validation on the input once it's entered. You as the developer are supposed to handle this by using CSS or JS to determine whether the field input is invalid, and flag it to the user as appropriate.
If you actually want to prevent non-digit characters from ever getting into the field, then the answer is yes, you need to use Javascript (best option is to trap it in a keyUp event).
You should also be careful to ensure that any validation you do on the client is also replicated on the server, as any client-side validation (whether via the HTML5 input fields or via your own custom javascript) can be bypassed by a malicious user.
It doesn't stop you from typing, but it does invalidate the input. You can see that if you add the following style:
input:invalid {
border:1px solid red;
}
I use a dirty bit of JS inline, it's triggered upon paste/keying (input).
Within your input tag add the following:
oninput="this.value=this.value.replace(/(?![0-9])./gmi,'')"
All it's doing is replacing any character not 0-9 with nothing.
I've written a tiny demo which you can try below:
Numbers only: <input oninput="this.value=this.value.replace(/(?![0-9])./gmi,'')"></input>
Firstly, in your Codepen, your inputs are not fully formatted correctly in a form.... Try adding the <form></form> tags like this:
<form>
<lable>input 1 </lable>
<input type='tel' pattern='[0-9]{10}' class='added_mobilephone' name='mobilephone' value='' autocomplete='off' maxlength='20' />
<br/>
<lable>input 2 </lable>
<input type="number" pattern='[0-9]{10}'/>
<br/>
<lable>input 3 </lable>
<input type= "text" name="name" pattern="[0-9]" title="Title"/>
</form>
Just add a check to the onkeypress event to make sure that the no alphanumeric characters can be added
<input
type="text"
placeholder="Age"
autocomplete="off"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
maxlength="10"
/>

HTML5 Validation - Easy Way to have real time validation?

I am using HTML5 for user validation. Here is a snippet of my code:
<input type="text" name="name" id="usernametb" title="Minimum 8 Characters, only letters
and numbers" pattern="^[A-Za-z0-9]{8,40}$" placeholder="Enter a Valid UserName" required />
I would like for user to get an error message either as soon as they type a username that doesnt match the validation pattern or when they tab to next field. Is there an easy way to do this with HTML5.
Right now, the error message doesn't display until I click "submit" and force a postback.
I have had good experiences with the parsley.js library:
http://parsleyjs.org/
Also for other input types (eg phone, email, URL) html5 can validate by itself, won't fix the example you have but it is very powerful and an insanely lightweight tool when it fits.
eg:
<input type="tel" name="cellPhone"></input>
Good luck!
This is a html5 validation plugin for jquery: http://ericleads.com/h5validate/ .
Quote from the plugin site:
Best practice realtime HTML5 form validation for jQuery. Works on all popular browsers, including old ones like IE6.
If you want to use your own javascript, use something like:
onkeyup="validateUsername(this)"
…so for example:
<input type="text" name="name" id="usernametb" title="Minimum 8 Characters, only letters and numbers" pattern="^[A-Za-z0-9]{8,40}$" placeholder="Enter a Valid UserName" onkeyup="validateUsername(this)" required />
Happy coding!

Why does my "oninvalid" attribute let the pattern fail?

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.