vendredi 20 janvier 2023

How do I validate a pattern set in an HTML tag thru JavaScript?

I'm very VERY new to JavaScript and I'm currently working on a challenge. I was given instructions to create a way to validate formats in a User ID field. I've tried about a thousand different methods using both Regular Expressions and functions in JS to have this User ID validation work, but nothing seems to function properly. I'm very lost and can't seem to make this work no matter the approach. I'd really appreciate if anyone could give me some advice or point out something I've been overlooking!

Here are the instructions (there are other parts to this challenge but I've chosen only the pieces of my code and instructions related to the User ID portion)

**Carefully follow the requirements below:

We prefer that you check the pattern match of the userid with javaScript rather than on the HTML input, but the HTML pattern match is ok if you can't figure out how to do it in javaScript.

Ask the user to input their first name, last name, a UserID, and a birthdate in type date format. The UserID must contain an uppercase, a lowercase, a number, and be 8 to 12 chars long.

Create a JS function to verify formats of the UserID field.

You will either need to use a For loop to iterate through your data fields character by character with JS functions like char.toUpperCase() and parsInt(char), or use Regular Expressions, to validate the UserID format.

Create an “Accept” button to execute your functions and create the following output:

If the UserID does not pass your verification, then print “Invalid UserID” to the Display window.

**And here is my code:

<!DOCTYPE html>
<html>
<body>

<h2>Type here</h2>

<div>

<label for="uid">User ID:</label><br>
<input type="text" id="uid" name="uid" pattern="(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,12}"><br>
<button type="button" onclick="validateUid()">Submit</button>

</div>

<p id="demo"></p>

<script>

function validateUid() {
let x = document.getElementById("uid").value;
if (x == "") {
    document.getElementById("demo").innerHTML = "Invalid UserID";
    return false;
}
}

</script>

</body>
</html>

This returns "Invalid UserID" when the field is left blank, but as per the instructions I need this to check the pattern I set in the HTML "uid" tag. I'm not sure how to get any kind of feedback. I've checked the Reg Ex and everything seems to be working like I want it to, but I don't know how to get a full check working. I'm sure it has something to do with the IF (x == "") portion but I genuinely have no idea what values to add. Again I'm sorry if this is a really stupid question but I'm very new and doing my best to learn on my own!

Aucun commentaire:

Enregistrer un commentaire