issues with the html 5 pattern attribute - javascript

I am trying to make sure the input field pattern should work, but all i am getting is an error that format is wrong
<input type="text" id="Phone" name="Phone" maxlength="14" value="" class="required" required="" data-msg-required="Please enter the Telephone number." pattern="/^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$/" placeholder="(XXX) XXX-XXXX">
<input type="submit">
the number is automatically formatting to (xxx) xxx-xxxx
so what is wrong here
also i am trying to remove the message it displays if the value is invalid and add the red border to the input field
var cell = document.querySelector("input[name='cellphone']");
cell.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
var ele = document.getElementById("cellphone");
$(ele).parents(".fui-form").addClass("fui-form-error");
};
})(), true);

If your goal is to just make sure that the input matches the pattern:
(XXX) XXX-XXXX, there are a couple things to take note of.
First of all, like Barmar said, when you use a regular expression in the pattern attribute of an HTML input element, that expression shouldn't be between forward slashes //.
Also, your regular expression is overly complicated. You can just do something like this:
// This javascript is just extra. Not important part.
const form = document.forms[0]
form.addEventListener('submit', e => {
e.preventDefault()
const { Phone: phone } = form.elements
// you could also do \s{1} for one space instead of a plain space if you want
console.log(phone.value, /\(\d{3}\)\s{1}\d{3}-\d{4}/.test(phone.value))
})
<form>
<input
type="text"
id="Phone"
name="Phone"
maxlength="14"
value=""
class="required"
required
data-msg-required="Please enter the Telephone number."
pattern="\(\d{3}\) \d{3}-\d{4}"
placeholder="(XXX) XXX-XXXX"
/>
<input type="submit">
</form>
Added a little extra JavaScript that will print the value of the input plus whether or not it matches the pattern. However, if you try adding any value inside the input that doesn't match the pattern, the form won't submit.
Let's go through each part of the regular expression:
I first escape these \(\), since I don't want to use them to capture a group. I want them to be part of the actual pattern
I want there to be exactly 3 numbers within those first parentheses. \d is shorthand for [0-9], and {3} means I want 3 of them.
There must be one space.
Then we require 3 numbers followed by a hyphen (-) followed by 4 numbers.
If you don't want the default error message to appear, and you want to do something else in case of an error, here's an option:
const form = document.forms[0]
const phone = form.elements.Phone
const regex = /\(\d{3}\) \d{3}-\d{4}/
form.addEventListener('submit', e => {
e.preventDefault()
console.log(phone.value, regex.test(phone.value))
})
phone.addEventListener('input', e => {
if (!regex.test(e.target.value)) {
if (!phone.classList.contains('error'))
phone.classList.add('error')
} else {
phone.classList.remove('error')
}
})
input[type='text'] {
outline: none;
border: none;
box-shadow: 0 0 1px rgb(0 0 0 / 15%);
}
input:not(:focus).error {
border: 2px solid red;
}
<form>
<input
type="text"
id="Phone"
name="Phone"
maxlength="14"
value=""
class="required"
required
data-msg-required="Please enter the Telephone number."
placeholder="(XXX) XXX-XXXX"
/>
<input type="submit">
</form>
I'm adding an event listener to the input which checks whether or not the user's input is valid after each new character typed. If the user leaves the input box (not focused), and the value of the input doesn't match our pattern, the input has a red border. If you're prefer some other behavior, you can just play with this code a little.

Related

HTML input validity initial state [duplicate]

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.
I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`
minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.
My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}
I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.
I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.
Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />

I have a problem with a function in javascript

I have a problem with my function in javascript, I try to replace automatically the first character when a user types any character, for example.
If the user types the letter a, in the input (with my function) replace that letter with the plus sign (+).
I want to add in my function a condition that allows to add automatically the plus sign at the beginning of the input and if is possible besides mustn't allow to delete the first character from the input.
Now my function allows to write only numbers.
<div>
<label>Write a phone number:</label>
<input type="text" maxlength="12" onkeypress="return number(event)"/>
</div>
<script type="text/javascript">
function number(e){
var tecla = e.keyCode;
if (tecla==8 || tecla==9 || tecla==13){
return true;
}
var patron =/[0-9+]/;
var tecla_final = String.fromCharCode(tecla);
return patron.test(tecla_final);
}
</script>
Updated, if you want past +44
Try to this one, and change if you need it
function phoneMask() {
num = $(this).val().replace(/\+4{1,2}|\D/g,'');
$(this).val("+44" + num);
}
$("#test").keyup(phoneMask);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Write a phone number:</label>
<input type="text" maxlength="12" id="test"/>
</div>

Validate a not required input

Is it possible to validate a phone number, but the same should not be required if left empty?
If the input is empty - the form should submit
If a phone number is entered, then its required that it be 10 digits.
If it doesn't match the 10 digits pattern - than the form should not submit
Please advise, thank you
If you use the required attribute you're game over. So don't.
its required that it be 10 digits
Use the ^\d{10}$ pattern:
input[type=text]:invalid{
border: 1px solid red;
}
<form>
<input type="text" pattern="^\d{10}$" />
<button>SUBMIT</button>
</form>
The form doesn't submits if
There's some value AND the value does not matches the regex in pattern.
The form submits if
There's no value
There's value AND has exactly 10 digits
You can use regex to match most phone numbers or an empty string.
var pat = /^$|^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
console.log(pat.test(''))
console.log(pat.test('8169428451'))
console.log(pat.test('(816)842-8455'))
console.log(pat.test('asdfs'))
function check(){
var pat = /^$|^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
var phone = document.getElementById('phone')
if(pat.test(phone.value))
{
document.getElementById("myForm").submit();
}
else
{
return false
}
}
<form id="myForm">
<input id="phone" type="text" />
<button onclick="check(); return false;">Go</button>
</form>

Input element that allowes only number with decimals, with AngularJS

I'm trying to create an input element that:
Holds a number (string or actual number doesn't matter).
You shall not be able to enter anything else but numbers and a dot(.).
You are allowed to enter two decimals.
If no decimals are entered, two decimals (i.e. .00) shall be added to the number when leaving the input element (on-blur).
I'm working with AngularJS (1.2) and watch $valid and $invalid on the containing form.
The input is valid when the value is a number with two decimals and the value is larger than 0.
I have tried to use:
<input ng-model="price" type="number" ng-blur="addDecimals()"/>
$scope.addDecimals = function(){
$scope.price = $scope.price.toFixed(2);
}
But then I can't add zeroes as decimals (.00). As toFixed() returns a string, the value is not allowed in the input and it becomes empty.
I have also tried to use
<input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" />
$scope.changed = function(){
// removes all charachters but numbers and one dot (.);
// examples:
// if value is '1a.t9' it will be changed to '1.9'
// if value is 'qwe' it will be changed to ''
// if value is 4 it will not be changed.
$scope.price = removeAllCharsButNumbersAndDot($scope.price);
}
$scope.addDecimals = function(){
if(parseFloat($scope.price) > 0)
$scope.price = $scope.price.toFixed(2);
else
$scope.price = "";
}
With this solution [form].$valid will be set to true if the value '0' is entered. [form].$valid will be set to false only when the user leaves the input element (on-blur) which is kind of ugly.
I have tried to use ng-pattern="/^\s*(?=.[1-9])\d(?:.\d{1,2})?\s*$/", but then ng-change will not fire.
You can use https://github.com/angular-ui/ui-validate. Ui-validate is great for this. Example:
<input type="number" ng-model="priceModel" ui-validate=" 'checkPriceModel($value)' ">
//Controller:
$scope.checkPriceModel = function(value){
return value <= 0;
}
<form name="theForm" id="theForm">
<input ng-change="changed()" id="priceId" type="number" min="1" name="priceName" ng-model="priceModel" required />
</form>
is the easiest (without extra modules)
If i am getting it right, you can try following
<form name="appTest">
<div
ng-class="{ 'has-error': appTest.app.$touched && appTest.app.$invalid }">
<input type="text" ng-model="vm.text" name="app" ng-pattern={define your pattern}>
</select>
</div>
If its invalid, 'has-error' class will get applied.
You don't need ng-change for this. You can just rewrite your html like this.
<form name="theForm" id="theForm">
<input id="priceId" type="number"
name="priceName" ng-model="priceModel" required min="0" />
<span class="error" ng-show="theForm.priceName.$error.number">
Not valid number!
</span>
</form>
You can read more about it here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D

Customize text for invalid fields in HTML

I am trying to display a customized message when the text entered does not match the pattern.
Following is the code I have used.
<input pattern="[a-zA-Z0-9]" name="firstName" id="firstname" required="" type="text" />
When I enter a valid text like 'akshay'; it is showing me the invalid message:
'Please match the requested format'
Also, I want to change this message to a customized one. I tried using the code given above but its is not working. Below is the code I have used below:
<script>
document.getElementById("firstname").addEventListener("invalid", function (e) {
var elem = e.target;
if (elem.value != "") {
e.target.setCustomValidity('Cannot contain special characters');
}
});
</script>
Please help me with this code.
Try to use oninvalid method in the input tag
<input pattern="[a-zA-Z0-9]*" name="firstName" id="firstname" required="required"
type="text" oninvalid="oninvalid="this.setCustomValidity(this.willValidate?'':'Cannot contain special characters')" />

Categories

Resources