I need to check email text before save it.
I want to fill in multiple email and seperate by ";" with following formats:
without a space "nicola#gmail.com;linda#gmail.com" (I succeed)
with a space "nicola#gmail.com; linda#gmail.com"
with mutiple spaces "nicola#gmail.com; linda#gmail.com"
And I cannot use type "email" because Edge don't support, so I back to use a standard "text" input.
$.validator.addMethod("pattern", function(value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp(param);
}
return param.test(value);
}, "Invalid format");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<div class="form-data-field">
<label class="fld">email</label>
<input class="content" type="text" name="email" data-formfield="Email" maxlength="150"
pattern="^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$|^NC$" />
</div>
I add \s* after [;] in pattern, and it works well
pattern="^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;]\s*(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$|^NC$"
Related
I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}
Good afternoon or at least in my country ^_^
I'm basically trying to do a full validation before submitting a form using the Vue Js library, on this snippet I'm checking if a input is empty.
const app = new Vue({
el: '#app',
data: {
name: null
},
methods:{
checkForm: function (e) {
if (this.name) {
return true;
}
if (!this.name) {
console.log("Please write your name :)")
}
e.preventDefault();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" #submit="checkForm" method="post">
<input type="text" v-model="name">
<input type="submit">
</form>
As you can see it works. But I want to increase security by adding a restriction for special characters and also detect a minlenght.
I try to search the internet for functions that allow me to do what I am looking for. But I can't find anything.
#catawP, i edited your snippet to allow checking for length and for special characters.
const app = new Vue({
el: '#app',
data: {
name: null,
email: null
},
methods:{
checkForm: function (e) {
e.preventDefault();
// if you want to check both fields
if(this.checkField(this.name, 'name') && this.checkField(this.email, 'email')) return true
// if you want to check only one field
if(this.checkField(this.email, 'email')) return true
},
checkField(value, field){
if (value) {
if(value.length < 10 && field === 'name'){ // check the length only for name field
console.log("The " + field + " should contain at least 10 characters!")
}else if(/[;,.]/.test(value) && field !== 'email'){ // exclude email field from this check
console.log('No special characters are allowed')
}else if(field === 'email' && !this.email.includes('#')){ // ex of custom checks for a specific field
console.log('Email field should contain #')
}else{
return true;
}
}
if (!value) {
console.log("Please write your " + field + " :)")
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" #submit="checkForm" method="post">
<label for="name">Name</label>
<input type="text" v-model="name" id="name">
<label for="email">Email</label>
<input type="text" v-model="email" id="email">
<input type="submit">
</form>
Checking the length can be done with the .length property. So you could add:
if(this.name.length < 30) {
console.log('Name must have 30 characters or more.');
}
Of course you don't want to use console.log for your form validation, but you did above in your first check so I repeated it. Also, 30 was arbitrary, you would change that to what you want.
As for "special characters", what do you mean? Do you want to disallow certain characters or only allow some characters? If you want to disallow some characters, you could use a regular expression and use test to see if it exists. For example:
let badchrs = /[$%\^]/;
if(badchrs.test(this.name)) {
console.log("you can't use $ or % or ^");
}
To only allow letters, you could do like so:
s = 'raymond';
badchrs = /^[a-z]/;
console.log(badchrs.test(s));
I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>
I am trying to achieve form validation of only alphabets but this regular expression doesnt seem to work
function check() {
var reg="/^[a-zA-Z]*$/";
var x = document.forms['frm'].name.value;
var y= document.forms['frm'].email.value;
if( x === ""){
alert('Name field cant be empty');
$("#nameone").focus();
return false;
}
else if (!reg.match(x)){
alert('NAME must contain alphabets only');
return false;
}
else if( y === ""){
alert('Email field cant be empty');
$("#emailone").focus();
return false;
}
else {
return true;
}
}
this is my form ,i have added the details ,the input fields
<form class="reg_form" name='frm' method="post" onsubmit='return check();' >
<div class="input-field col-md-4">
<input type="text" placeholder="1. Name" name="name" id='nameone'/>
</div>
<div class="input-field col-md-4">
<input type="text" placeholder="2. Email" name="email" id='emailone' />
</div>
<div class="input-field col-md-4 ">
<input type="text" placeholder="3. phone" name="phone" />
</div>
</form>
In this case, your code isn't working 'cause your regex was set as a string in the line:
var reg="/^[a-zA-Z]*$/";
The regex was suposed to be set without quotes:
var reg=/^[a-zA-Z]*$/;
I suggest that instead of the method 'match', you use:
else if (!reg.test(x)){
This is more performatic and return a boolean value.
Instead of...
var reg = "/^[a-zA-Z]*$/"; // produces a **string**
You should omit the surrounding quotes:
var reg = /^[a-zA-Z]*$/; // produces a **Regex object**
The second uses javascript inline Regex syntax, with the slashes functioning as delimiters.
Furthermore you can use the simple .test() function to check if a string conforms to a Regex or not.
Demo:
var reg = /^[a-zA-Z]*$/;
console.log(reg.test("ABcd"));
console.log(reg.test("123"));
you can use
string.match("^[a-zA-Z]+$$");
you will get true if the string contains only letters and false otherwise
I have two fields, the NIC and the username. Their validation are
NIC check for numbers or characters
username field must contain more than 8 characters including the date
of birth from the NIC.
So far I tried this for my NIC.
function validateNIC()
{
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
message1.innerHTML="Length must be 14 characters";
} else{
message1.innerHTML="Length is good";
}
}
<div class="form-group">
<label for="username"><span class="req">* </span> NIC NUMBER:</label>
<input class="form-control" type="text" name="NIC" id = "NIC" required onkeyup = "validateNIC();" maxlength=14 />
<span id="message1"></span>
</div>
And for my username I tried this.
function Validate(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
<div class="form-group">
<label for="username"><span class="req">* </span> User name:</label>
<input class="form-control" type="text" name="username" id="txt" onkeyup="Validate(this)" maxlength=14 required />
<div id="errLast"></div>
</div>
My validation for the NIC is not quite working.It keeps showing
"Length must be 14 characters" even if the length is good.
And for the username part, can anyone tell me how to do it ? Is
there an array I must do or something ? An example of the NIC is
T2108974302906 where 210897 is the DOB.
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
Here NIC refers to the DOM element, not the value of that input element.
You want to use nic.value.length.
As for the username, your RegEx looks strange [^a-zA-Z-'\n\r.]. This set matches characters that are not in the set. Why did you put \n and \r?
Anyway, if you are using a <form> element to submit these field, I suggest you use pattern attribute. You can test yoru patterns on http://regex101.com/
To extract the DOB:
<input pattern="^T[0-3]\d[0-1]\d{10}$">
validateNIC() {
var nic = document.getElementById('NIC');
var isValid = /^T[0-3]\d[0-1]\d{10}$/.test(nic.value);
var dob = nic.value.substring(1, 7);
}
var nic = document.getElementById('NIC');
This statements gets the input element - not its value. You need to get its value as such:
var nic = document.getElementById('NIC').value;
Then, you can compare the length to 14. I would also suggest using !== instead of !=.
Username validation - why are you replacing the value if you're trying to validate? And why is your max value 14 and not 8?