-2

I would like to make a validation of a form. More precisely, I need to ask for my user to fill the form with the following conditions:

  1. email: it must have letters and one @,
  2. password: it must have letters, numbers and only lower letters. How can I ask it to my users in JS?

I have here the code for "name" but I don't know which method use to others:

let nome = document.querySelector('#name')
nome.addEventListener('keyup', () => 
    {if(nome.value.length <= 5)
        {nome.setAttribute('style', 'border-color: red')}
    else
        {nome.setAttribute('style', 'border-color: green')}});

Indeed I have been using, now, this code here. These are the variables:

let nome = document.getElementById('nome');
let nomeCombinaRegex = nome.value.match(/^((\b[A-zÀ-ú']{3,40}\b)\s*){2,}$/);
let nomeVerde = nome.setAttribute('style', 'color:green');
let nomeRed = nome.setAttribute('style', 'color:red');

This is the HTML:

<div class="form">
<i class="bi bi-person"></i>
<input id="nome" type="text" required autofocus placeholder="Nome" oninput="nameValidate()">
</div>

This is the JS Function:

function nameValidate()
    {if(nomeCombinaRegex)
        {nomeVerde}
    else 
        {nomeAlert;
        nomeRed}}

Question: What am I doing wrong? the code doesn't work (I'm new in JS)

Bruhlickd
  • 69
  • 7
  • 1
    I'd use regex, but why are you limiting passwords to be weak? – Nikki9696 Aug 16 '22 at 16:50
  • regex might be like `return /^[a-z0-9]*$/.test(str);` – Nikki9696 Aug 16 '22 at 16:51
  • Possible dup of https://stackoverflow.com/questions/46155/how-can-i-validate-an-email-address-in-javascript and/or https://stackoverflow.com/questions/388996/regex-for-javascript-to-allow-only-alphanumeric – danh Aug 16 '22 at 16:52

3 Answers3

1

Regular expressions can be used to describe strings with certain conditions. For example, you can test your email and password strings as follows:

const emailRegex = /^[A-za-z]+@[A-za-z]+$/
const passwordRegex = /^[a-z0-9]+$/

emailRegex.test(email)
passwordRegex.test(password)
Hussain Khalil
  • 1,520
  • 2
  • 15
  • 24
1

the most fun and easy way to solve this issue is using regex, you can play with it here. Similar question is here , you can create regex according to your need

function matchString() {
  var string = document.querySelector('#name');

  // it matches small and capital alphabeds,
  // if you dont want number remove 0-9
  // this also work for only alphabeds and @ ([a-zA-Z0-9])+@ or ^([a-zA-Z0-9])+\@
  var result = string.match(/^([a-zA-Z0-9_\.\-])+\@/g);
  document.write("Output : " + result);
}
Ayaz
  • 67
  • 1
  • 9
1

Do not simply change the styles. Instead, inform the browser that the input is invalid. This provides a better user experience, especially for people using screen readers.

For email addresses, browsers already have a built-in way to check whether they are valid. For more complex conditions, you can use the pattern attribute or the "input validity" methods.

const email = document.getElementById("email-input");

const pass = document.getElementById("pass-input");
pass.addEventListener("input", (ev) => {
  if (pass.value.match(/\d/) && pass.value.match(/[a-z]/) && !pass.value.match(/[A-Z]/)) {
    pass.setCustomValidity("");
  } else {
    pass.setCustomValidity('"' + pass.value + '" is not a valid password.');
  }
});

const form = document.getElementById("signup-form");
form.addEventListener("submit", (ev) => {
  alert(`Success!\nE-mail: ${email.value}\nPassword: ${pass.value}`);

  // Prevent the navigation
  ev.preventDefault();
});
input:valid {
  border-color: green;
}
input:invalid {
  border-color: red;
}
<form id="signup-form">
  <label for="email">E-mail</label> <input type="email" name="email"  id="email-input" required><br>
  <label for="pass">Password</label> <input type="password" name="pass" id="pass-input" required><br>
  <button type="submit">Submit</button>
</form>
D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • Why I can't use this one: function cadastrarButton() let passw = document.getElementById("#senha"); {if (passw.value.match(/\d/) && passw.value.match(/[a-z]/) && !passw.value.match(/[A-Z]/)) {alert('Well done!')} else {alert('It is all a mess!')}}; – Bruhlickd Aug 16 '22 at 18:30
  • I'm assuming you would call that function when the submit button is clicked. You generally should not add `click` event listeners to the submit button and you should instead add `submit` event listeners to the form. The form can only be submitted if all of its inputs are valid. If they're not, the browser will tell the user which inputs need to be changed. I have edited my answer; take a look at it. – D. Pardal Aug 16 '22 at 18:57