Setting custom HTML5 validity message property ignores pattern regex - javascript

I'm using the pattern attribute in an HTML5 input. It works fine, until I add a custom message using setCustomValidity. All this is supposed to do is
Sets the validationMessage property of an input element.
But instead my pattern is ignored. If I comment out the setCustomValidity, the pattern works.
HTML
<form>Country code:
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
</form>
JS
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
console.log($(this).prop('validity'));
var valid = $(this).get(0).checkValidity();
console.log(valid); });
http://jsfiddle.net/hrtsz50s/

use reportValidity(); insted of checkValidity(); and when you call the function clear the validity with an empty string first!
$('input').get(0).setCustomValidity("It's wrong");
$('input').on('input', function () {
this.setCustomValidity('');//Add this!!
console.log($(this).prop('validity'));
var valid = $(this).get(0).reportValidity();//here
console.log(valid); });
edit
Got it working in this fiddle: http://jsfiddle.net/hrtsz50s/1/

Related

How to force validate data of the HTML 5 input from jquery?

I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>

JavaScript regular expression mobile phone number format

1.XXX-XXX-XXXX
2.XXXXXXXXXX
I would like to know the regular expression of the format.
Modifying the existing sources will yield results.
var regExp = /^01([016789]?)-([0-9]{3})-([0-9]{4})$/;
var regExp = /^01([016789]?)[0-9]{3}[0-9]{4}$/;
A statement to check the condition.
I wonder if the contact form is also correct.
var test is a text field that receives input.
if(!regExp.text) {
alert(""phone number format is not valid.");
document.getElementById('phone').focus();
return ;
}
I'm not quite sure what you are trying to achieve, but maybe this example helps:
https://jsfiddle.net/xu9fcbxt/
Notice: jQuery required
Code:
JS:
$(document).ready(function(){
var regExp = /^01[5-7][1-9]-[0-9]{3}-[0-9]{4}/;
$('#phone').focusout(function(){
var text = $('#phone').val();
if(!regExp.test(text)){
alert('not a valid phone number');
}
});
});
HTML:
<input id="phone" type="text" />
This would check if the number has a format like 0151-123-4567

Calling jQuery functions on inputs in Bootstrap Modal

I have a couple of jQuery functions that validate an input field according to a regex. When I have a form embedded on a page, they work fine. However, when I try to use them inside of a Bootstrap Modal they do not work.
Any ideas?
<input class="form-control input-lg validate-email" id="email" name="email" minlength="2" type="text" placeholder="Email">
$('.validate-email').on('input', function() {
var input = $(this).val();
var regex = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var is_email = regex.test(input);
if(is_email){
$(this).removeClass("invalid").addClass("valid");
} else{
$(this).removeClass("valid").addClass("invalid");
}
});
Once again, this code works when the form is on a page, but not when the form is in a Bootstrap Modal.
One more detail, the valid and invalid are CSS classes that change the background-color of the field to change. If I skip the jQuery and just hardcode an invalid class in the <input> it shows the invalid class. So I know it is the jQuery.
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}

How to display message with the help of jquery?

i m trying to do a validation using jquery.
Enter Account no:
here is my html code
<input type="text" name="Assets" id="Assets" size="25" /><br />
<div id="eb"> Please Enter Valid Account no </div>
Enter Amount<input type="text" name="Liability" id="Liability" size="25" /><br />
and here is my jquery code
$(document).ready(function(){
$("#Assets").change(function(){
var Assets = $('input#Assets').val();
var expression=/[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets == "" || Assets == " ") {
$('#eb').show();
}
else if(Assets.test(expression)){
$('#eb').hide();
}
$('#eb').toggle();
}
i want to display a mesage when user write a account no then at a time he can see the message that Please Enter Valid Account no and if he insert correct then that message can be hide.
here is my jsfiddle - http://jsfiddle.net/BzdfN/5/
please help
Try this code:
$(document).ready(function () {
$("#Assets").change(function () {
var Assets = this.value;
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets.match(expression)) {
$('#eb').hide();
} else {
$('#eb').show();
}
});
});
This is a suggestion for more simple code. Notice I used match() which takes a regex as paramenter, if you want to use test() you should use the value/string as paramenter and use like expression.test(Assets).
Fiddle
About your code/fiddle:
you missed adding jQuery library to the fiddle
you missed ) closing the change() function
you missed }) closing the ready() function
you used test() with wrong order, check my text above about match() and test()
your fiddle with corrections: Fiddle
jQuery was not included and multiple syntax errors
$(document).ready(function () {
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
$("#Assets").change(function () {
$('#eb').toggle(!expression.test(this.value));
})
})//missing brackets
Demo: Fiddle
Try this - http://jsfiddle.net/dangoodspeed/BzdfN/9/ I made a bunch of changes, including activating jQuery, closing some functions, and reversed Assets and expression for the .test call
else if(expression.test(Assets)){

Validate TextBox In JavaScript

i need a validate textbox which is accepted like this $250.00 here is '$' will accepted only one time and then never accepted '$' as well as '.'(dot).
You could use a masked input for example
your mask would be
$('#input').mask('$9?.99');
You can do:
var x = document.getElementById('your-text-box').value;
if(x.match(/^\$[0-9]+\.[0-9]+$/) == null) {
// invalid
}
else {
// valid
}
The regex /^\$[0-9]+\.[0-9]+$/ will match any string meeting the following constraints
Should start with a $
Should have 1 or more numbers after the $
Should have a . after the first set of numbers
Should end with 1 or more numbers after the .
Is jquery an option?
Here is a jquery solution. First of all I wouldn't validate expecting user to put '$'. I would put that outside the form and just allow people to enter the amount. That's weird, but I guess I don't really have the context on what you are doing. See Jquery validation:
$("#myform").validate({
rules: {
field: {
required: true,
digits: true
}
}
});
This is using digits to allow only numbers. Otherwise if you really need $ in there you need to create a custom validation rule.
<!-- wherever your jquery file is -->
<script src="../../jquery.min.js"></script>
<input type="text" id="cost"><input type="button" id="check" value="Check!">
<script>
// jquery solution
$(document).ready( function (){
$('#check').click( function (){
var cost = $('#cost').val();
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
});
});
</script>
Of course you can use pure java script as well to reduce the dependency
<input type="text" id="cost">
<input type="button" id="check" value="Check!" onClick="check();">
<script>
// Pure Javascript Solution
var check = function (){
var cost = document.getElementById('cost').value;
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
}
</script>

Categories