I want to validate my form now, and I wrote some code, it's working perfectly for length constraints but I want to use Regular Expression to filter the values of each element.
I found from a forum, these Regular Expressions:
for Full Name: var regex = /^[a-zA-Z ]$/;
for Phone: var regexPhone= /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
I guess the HTML5 (input:type email) is enough for email validation
Also I want to do this with the name, that when I type the full name, the first letters change to uppercase letters. For example--> input="john smith", changes to "John Smith".
This is my code:
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if(pedio.id.indexOf("Name")!=-1){
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if(pedio.id.indexOf("Phone")!=-1){
if (pedio.value.length!=10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail"autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br>
-If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Option 1: You can use text-transform: capitalize CSS property which will automatically do the task of converting a name from john cena to John Cena.
Check the example below in the CSS
Option 2:
I have added a new input called Nick name which uses javascript to do the same task.
I have used keyup handler to capture the all key input event so that we can execute a piece of code which will do the job on capitalizing the name.
The result is simple string manipulation which splits the name with <space-character> and converts the first character to uppercase and joins the same with rest of the string.
document.addEventListener("DOMContentLoaded", function() {
document.querySelector("#NickName").addEventListener("keyup", capitalizeName);
});
function capitalizeName() {
if (!this.value) return;
var aNewName = this.value.split(" ").map(function(name) {
return name.charAt(0).toUpperCase() + name.substring(1);
});
this.value = aNewName.join(" ");
}
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if (pedio.id.indexOf("Name") != -1) {
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if (pedio.id.indexOf("Phone") != -1) {
if (pedio.value.length != 10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
#Name {
text-transform: capitalize;
}
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="text" id="NickName" name="NickName" placeholder="*Nick name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail" autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br> -If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Hint:
The RegExp object has a method test which when given a string argument returns true if there was at least one match in the str or false. MDN Documentation
Used as /regexp/.test(str). You already have code that tests for length. You want to test for the length AND for this regex.
When you want to capitalize the first letter of each word, that is called Title Case. There's an excellent answer here for that part of your question
Related
I want to verify and validate a form in HTML, and insert messages in Front if necessary ("eg.Pseudo/Username not long enough"), which will serve as a "new user" form for a website.
I want to start by understanding my mistake for the "Pseudo" verification and validation.
I currently have the following in HTML:
<form id="formNouveau" onsubmit="return valideForm2()">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS (focusing on the pseudo validation):
function valideForm(){
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
function valPseudo(text)
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of text.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert ("Please write a pseudo");
if (letterCount + numberCount > 40)
alert ("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert ("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert ("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert ("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
}
What do you think?
Thank you!
You have a mix of variable names in the function and a sub function with incorrect syntax. You're not preventing the form from submitting. Fixed both and it works:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert("Please write a pseudo");
if (letterCount + numberCount > 40)
alert("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
function valideForm2(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
console.log(valPseudo);
function validate(text) {
let letters = "abcdefghijklmnopqrstuvwxyz";
let numbers = "0123456789";
let letterCount = 0;
let numberCount = 0;
for (let character of text.toLowerCase()) {
if (letters.includes(character)) ++letterCount;
else if (numbers.includes(character)) ++numberCount;
else return false; //A non [a-zA-Z0-9] character was present
}
if (text == "") alert("Please write a pseudo");
if (letterCount + numberCount > 40) alert("Pseudo is too long"); //The name is too long
if (letterCount + numberCount < 5) alert("Pseudo is too short"); //The name is too short
if (letterCount < 1) alert("one letter needed at least"); //There aren't enough [a-zA-Z] characters
if (numberCount < 1) alert("one number needed at least"); //There aren't enough [0-9] characters
return 0; //Everything is okay!
}
validate(valPseudo);
}
const form = document.getElementById("formNouveau");
form.addEventListener("submit", valideForm2);
Try this JS code instead, it has the same functionality but has some modifications, the main problem was regarded to e.preventDefault() which forces page not to reload. Moreover you had some little bugs. For more information on preventDefault you can visit link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You're better off testing the input against a REGEX expression rather than testing for each failure case...
There a numerous REGEX testers and cheat-sheets online for what you're trying to do.
I'm trying to create a form where the user fills out their details, the form currently doesn't send if one of the fields has no input in it because I have added in a "required" into each of the tags to create the field. I have written some JavaScript to open a popup if the form is valid but it isn't working, the form submits to my PHP database but the pop up window doesn't appear. Any thoughts? Here is my current JavaScript.
Code for the form fields -
label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..." required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..." required>
<label for="phonenumber">Phone Number</label>
<input type="text" id="phonenumber" name="phonenumber" placeholder="The best number to contact you on..." required>
Code to call the script -
<button onclick="myFunction()">Submit</button>
JavaScript validation
<script>
function validateForm() {
var x = document.forms["fname"].value;
var y = document.forms["lname"].value;
var p = document.forms["phonenumber"].value;
if ([x == "", y =="", p ==""]); {
alert("Name must be filled out");
return false;
}
}
function myFunction() {
if (x == "") {
return false;
}
else {
alert("Thank you for making an enquiry, a member of our team will be in contact with you soon.");
}
}
Try Code Below
<script>
function validateForm() {
var x = document.forms["Forms"]["fname"].value;
var y = document.forms["Forms"]["lname"].value;
var p = document.forms["Forms"]["phonenumber"].value;
if (x == "" && y =="" && p ==""); {
alert("Name must be filled out");
return false;
}
else
{
return true ;
}
}
<form name="Forms" onSubmit="return validateForm() "><input type="text" name="fname" /><input type="text" name="lname" /><input type="text" name="phonenumber" /></form>
or you can simply use required in every input
I'm trying to create a form validation using HTML and pure JavaScript as a part of my assignment. However, the age and password validation don't seem to work even with tinkering a lot with code. The age is supposed to be valid if it is between 18 to 60 and the password must be the same as well as according to regex.
Here's the extended code:
Edit: the uage code has been edited but still doesn't work as intended.
function checkPassword(str) {
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
}
function checkName(str) {
var ge = /^[a-zA-Z ]+$/;
return ge.test(str);
}
function mytq() {
var uname = document.forms.formvalidation.fullname;
var uemail = document.forms.formvalidation.email;
var uage = document.forms.formvalidation.age;
var upwd = document.forms.formvalidation.password;
var vpwd = document.forms.formvalidation.pwdrpt;
if (uname.value != "") {
if (!checkName(uname.value)) {
window.alert("Please enter a valid name");
uname.focus();
return false;
}
}
if (!(uage < 16 || uage > 60)) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}
if (uemail.value.indexOf("#", 0) < 0 && uemail.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid email");
uemail.focus();
return false;
}
if (upwd.value != "" && upwd.value == vpwd.value) {
if (!checkPassword(upwd.value)) {
window.alert("The password you entered is not valid");
upwd.focus();
return false;
}
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript">
</script>
</head>
<body>
<form name="formvalidation" method="POST" onsubmit="return mytq();" action="#">
<h1>Welcome to FTN.</h1>
<p>Fill this form before</p>
<hr>
<label for="name"><b>Full Name</b></label>
<input type="text" name="fullname" placeholder="Full Name" required>
<label for="email"><b>Email</b></label>
<input type="text" name="email" placeholder="Email" required>
<label for="age"><b>Age</b></label>
<input type="number" name="age" required>
<label for="password"><b>Password</b></label>
<input type="password" name="password" placeholder="Password" required>
<label for="password-repeat"><b>Re-type password</b></label>
<input type="password" name="pwdrpt" placeholder="Re-type Password" required>
<hr>
<p>By creating this account, you are agreeeing our terms and condition</p>
<button type="submit" class="registerbtn">Submit</button>
</form>
</body>
</html>
Your age comparison is flawed. If you wish to ensure that the age is greater than 16 and less than 60, you should simplify it to
if(uage < 16 || uage > 60) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}
I'm trying to create one function that will check that a field is not blank, contains only letters and spaces. Validating that the field contains letters and spaces only does not appear to work as anything that's put in the field will return the alert message.
I'm trying to say:
If the name field is NOT letters and spaces then display this alert "...". Else return true.
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (x!==/^[A-Za-z ]+$/) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
else {
return true;
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
missing } at end of script and missing ; at else if
and use regex for check only letter and space
function validateForm() {
var regex = new RegExp("^[a-zA-Z ]+$");
var x = document.forms["newsletterForm"]["name"].value;
if (x == null || x == "") {
alert("Name must not be blank");
return false;
} else if (!regex.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)");
return false;
} else {
return true;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
Hi You can use regex for that
var regexExp = /^[a-zA-Z\s]*$/;
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
alert(x)
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (!regexExp.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
I'm thinking that the problem is your use of !==. !== would be looking for an absolute match between x and your regular expression object - that is, is x that regular expression object; not does it match that expression.
What about this:
else if (! /^[A-Za-z ]+$/.test(x))
use typeof
try
if(x == null || typeof x !== 'string')
{
//code here
}
An empty string isn't a valid value to check against.
please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>