I have a problem with input validation using pattern and required attribute. The idea is that I want to use my own title, not the browser's. When I want to complete the input with characters that not correspond with the regex (numbers), message 'Only letters allowed' displays near the input. But when I complete with letters it shows me the same message that my characters are incorrect. Who knows what is the problem? Thank you.
<script type="text/javascript">
function validation (textbox) {
var regex = /^[a-zA-Z]+$/;
if (textbox.value == '') {
textbox.setCustomValidity('Required field');
}
else if(!regex.test(textbox.value)){
textbox.setCustomValidity('Only letters allowed');
}
else {
textbox.setCustomValidity('');
}
return true;
}
FORM input:
<input type="text" id="first-name" name="first_name" placeholder="First Name" oninvalid="validation(this);" required="requied" pattern="/^[a-zA-Z]+$/"/>
Related
Please i am trying to specify a pattern in the email input field in my form that it takes on lowercase words and if uppercase words are inputted in the email field it give an error and the form isn't submitted.
You can try this with javascript.
function checkText(e) {
const text = e.target.value;
if (text && (text === text.toUpperCase() || text.substr(-1) === text.substr(-1).toUpperCase()))
console.log('No upper case allowed')
}
<input type="text" oninput="checkText(event)">
Working FIddle
I use input type=email in my application. Prior to that in the old system developers user input type=text. Recently I was asked to fix the 'issue' in my code. The problem was reported by user when entering email address in the input field, accidentally empty space was entered on the end. Then user tried to Save the form, and error message was displayed under the email field This field is mistyped. I'm wondering if this is the way type=email should work and prevent empty space in the email address fields?
I tested this problem in Chrome and empty space will not be detected, but in Firefox will be and error message will show up.
$("#save").on("click", function() {
console.log(verifyFields('my-form'));
if (verifyFields('my-form')) {
alert('Saved!');
}
});
function verifyFields(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
//'valueMissing': "This field is required",
//'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
const invalidInputs = [];
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
var label = curItem$.data("label");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
if (curItem$[0].validity['valueMissing']) {
var reqMsg = label ? label + " field is required" : "This field is required";
errMsg.push(reqMsg);
}
if (curItem$[0].validity['customError'] && dispfld) {
errMsg.push(dispfld);
}
if (curItem$[0].validity['patternMismatch'] && dispfld) {
errMsg.push(dispfld);
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
errMsg.push(hdlMap[prop]);
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
invalidInputs.push(curItem$);
isValid = false;
} else {
curItem$.removeClass("is-invalid");
}
}
});
if (invalidInputs.length) {
invalidInputs[0].focus();
}
return isValid;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="my-form" id="my-form">
<input type="email" name="user-email" id="user-email" required>
<button type="button" id="save">Save</button>
</form>
a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them (A).
So in this case you have an unfortunate scenario where the space isn't in the middle of the email address, but at the beginning or end. But if you look at the validation that the browser follows for this input type, it still won't be allowed.
You have two options:
Set it back to input type="text", but set the same validation pattern that applies for emails: <input type="text" pattern="/^[a-zA-Z0-9.!#$%&'*+\/=?^_{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" /> and then modify that regex to allow for ending spaces (though you need to check on the back-end to make sure it will allow them, or otherwise you need to do a .trim() to remove those surrounding spaces.
Do a .trim() on your input after the user exits the input; removing whitespaces at the start or end.
(A) According to this answer:
space and "(),:;<>#[] characters are allowed with restrictions (they are only allowed inside a quoted string...
So in my registration form I have this field:
<div class="form-group">
<label for="RegisterModel_Password">Password</label>
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password" class="form-control"
required="required" minlength="8"/>
</div>
As you see, I'm using jQuery validation attributes to ensure that the password includes at least 8 characters. So, I want to check if password contains uppercase and number, if not, field is not valid. I downloaded additional method for jQuery Validation plugin named "pattern" and added her in head tag.
I tried to do this as follows but it didn't worked.
$("#formRegister").validate({
rules: {
RegisterModel_Password: {
pattern: /^[a-zA-Z][0-9]/
}
}
});
I assume that the pattern is wrong, but I'm not sure whether the use is correct.
Thank you for your help.
Chains of regular expressions are too hard for me ( I have never tried to learn them lol ). So here is my solution:
jQuery.validator.addMethod("passwordCheck",
function(value, element, param) {
if (this.optional(element)) {
return true;
} else if (!/[A-Z]/.test(value)) {
return false;
} else if (!/[a-z]/.test(value)) {
return false;
} else if (!/[0-9]/.test(value)) {
return false;
}
return true;
},
"error msg here");
And simply I use it like a attribute:
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password"
class="form-control"
required="required" minlength="8"
passwordCheck="passwordCheck"/>
Thanks for your answers.
You can add your custom validation using $.validator.addMethod() like:
$.validator.addMethod("validation_name", function(value) {
// at least 1 number and at least 1 character
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
});
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>