Implementing password validation using ng-pattern allows for a more secure and

How can I validate a password using ng-pattern? The regular expression I'm using in my model works fine, but it only displays an error message if the password is shorter than 7 characters. It doesn't show an error if the password is also in the wrong format. Can someone help me understand why?

Model:

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}$", ErrorMessage = "Your password is too short (minimum of 7 characters) or not in the correct format.")]
[Required(ErrorMessage = "Please enter your password.", AllowEmptyStrings = false)]
public string Password { get; set; }

Registration.cshtml:

<input type="password" style="width: 600px" class="form-control" name="Password" id="Password" ng-pattern="^(?=.*[a-z])(? =.*[A-Z])(? =.*\d)[a-zA-Z\d]{7,}$" ng-model="User.Password" ng-minlength="7" ng-class="submitted?'ng-dirty':''" required />
<span class="error" ng-show="(form.Password.$dirty || submitted) && form.Password.$error.required">Please enter your password.</span>
<span class="error" ng-show="(form.Password.$dirty || submitted) && (form.Password.$error.minlength || form.Password.$error.pattern)">Your password is too short (minimum of 7 characters) or not in the correct format.</span>
<span class="success" ng-show="(form.Password.$dirty || submitted) && form.Password.$valid">Your password has a sufficient length and is in the correct format.</span>

Answer №1

To properly format your regular expression, be sure to include the "/" before and after it. Also, eliminate any spaces inside the positive lookahead as advised by @MikeMcCaughan. For instance, modify (? = to (?=

ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}$/"

Answer №2

Transform the pattern to

/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$/

<input type="password" style="width: 600px" class="form-control" name="Password" id="Password" ng-pattern="/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$/" ng-model="User.Password" ng-minlength="7" ng-class="submitted?'ng-dirty':''" required />
                <br/>
                <span class="error" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.required">Required</span>
                <span class="error" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.minlength">Minimum of 7 characters</span>
                <span class="success" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.pattern">Invalid</span>

Check out the demo link here https://plnkr.co/edit/Xo1qfEHS2NrdUHyHDjml?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to update the accessor value of my react table depending on certain data conditions?

const data = { name:"test1", fclPrice:100, lclPrice:null, total:"50" } and here are the two columns: const Datatable = [ { Header: 'Name', accessor: 'name' }, { Header: 'Price', ac ...

I continuously receive the error message "StripeInvalidRequestError: Insufficient funds in Stripe account" despite the fact that there are adequate funds available

I'm in the process of transferring funds from my test mode Stripe account to another connected Stripe account. The balance in my test mode account is sufficient and there are no pending funds. However, I keep encountering a "StripeInvalidRequestError: ...

The jQuery click event is only triggering once in a new scenario

UPDATE: For more information, check out the site I am in need of a solution to remove all the IDs from each .item_index li within the div and then assign the id #servico_ativo to the one that has been clicked on. However, I am facing an issue where this p ...

JSX Transform error arises in Flask and Reactjs integration

Recently, I've delved into the world of ReactJS with a Python Flask Backend. While trying to render the template via Flask, Chrome Console shows this client error: Error: Cannot find module 'jstransform/visitors/es6-templates-visitors' ...

The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatl ...

Processing JSON in PHP after an AJAX POST request

In the scenario where JavaScript is used to make an ajax request: index.js- var dataFeedback = $("#feedback_popup_message_body").val(); var jsonObj = JSON.stringify({dataFeedback: dataFeedback}); $.ajax({ url: "index.php", type: 'POST' ...

How to load an iframe only upon clicking on a link

I am struggling to make the iframe popup appear only when a specific class link is clicked. Here is my HTML and JS code: Unfortunately, nothing happens when I click the link with the class 'aclass'. I have updated my JavaScript, but the issue ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

Does the rendering of HTML get blocked by CSS in the <head> section like it does with javascript?

While it's common practice to keep JavaScript at the bottom of the HTML document, does the same rule apply for CSS as well? I understand that we can't place external CSS files outside the HTML document. ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Is it possible to determine if the user is able to navigate forward in browser history?

Is there a way to check if browser history exists using JavaScript? Specifically, I want to determine if the forward button is enabled or not Any ideas on how to achieve this? ...

Issues arise when utilizing external scripts alongside <Link> components in ReactJS, resulting in them becoming unresponsive

I'm experiencing some difficulties with an external script when using <Link to="/">. The script is included in the main layout file index.js as componentDidMount () { const tripadvisorLeft = document.createElement("script"); tripadvisorLef ...

Trying out a React component that relies on parameters for connection

Having an issue while attempting to test a connected react component that requires a props.params.id in order to call action creators. During the testing process, when checking if the component is connected to the store, an error "Uncaught TypeError: Canno ...

Navigational elements, drawers, and flexible designs in Material-UI

I'm working on implementing a rechart in a component, but I've encountered an issue related to a flex tag. This is causing some problems as I don't have enough knowledge about CSS to find a workaround. In my nav style, I have display: flex, ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

Ways to retrieve information and functions from defineExpose in Vue

`I am attempting to call a method from a child component within the parent component in Vue using the composition API. I have defined the method inside defineExpose, but I am unable to access it in the parent component. Hero.vue (ChildComponent) <templ ...

"Unleash the power of the Web Audio API by releasing

Currently, I am utilizing the WEB Audio API within a Webapp to render an Audio Signal. However, I have encountered an issue where Chrome's RAM usage gradually increases as it loads an audio file every second. Unfortunately, I am unsure of how to relea ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...