Niels
Niels

Reputation: 145

How to use HTML form validation on button click?

I'm creating a application using SyncFusion and Blazor. In this application I have a login page which looks like this:

enter image description here

Using this code:

<EditForm Model="@ModelValue">
    <SfTextBox @ref="user" Placeholder="E-mail" Created="@onCreateUser" CssClass="custom-login" Type="InputType.Email" @bind-Value="@ModelValue.Email" required></SfTextBox>


    <SfTextBox @ref="password" Placeholder="Password" Created="@onCreatePassword" CssClass="custom-login" Type="InputType.Password" @bind-Value="@ModelValue.Password" required minlength="7"></SfTextBox>

    <SfCheckBox Label="Stay Signed In" @bind-Checked="rememberUser" CssClass="stay-signed-in-checkbox"></SfCheckBox>
    <SfButton CssClass="forgot-password-button">Forgot Password?</SfButton>

     <SfButton CssClass="login-button" OnClick="validateForm">LOGIN</SfButton>
</EditForm>

@code {
SfTextBox user;
SfTextBox password;
private bool rememberUser;
private User ModelValue = new User();

public void validateForm()
{ 

}

/*ICON*/
public void onCreateUser()
{
    this.user.AddIcon("prepend", "oi oi-person");
}

public void onCreatePassword()
{
    this.password.AddIcon("prepend", "oi oi-key");
}
}

In this form are html browser validation popups applied(automatically). These work kind of weird in my situation therefore i created a video illustration it properly:

https://drive.google.com/file/d/1PhETRPkgDag_DHWYlBFJL1qnodxDpaQ_/view?usp=sharing

As u can see the email field works fine, html form validation occurs every time when button is pressed. In the Password field this is not the case, theres required a minimum of 7 characters and when i press submit button with only 3 characters filled in im not getting any warnings.

Does someone know how to fix this?

Upvotes: 2

Views: 1013

Answers (1)

Vencovsky
Vencovsky

Reputation: 31655

If you want to use the html5 form validation, the minlengthattribute won't work. If you want to do that validation you should use pattern attribute and pass it like pattern=".{7,}". This is explained in this answer.

If you want to use the blazor validation (which is much better and recommended), you need to use data annotations in your User model.

For your particular case, you can use the MinLength attribute.

public class User 
{
    // other propeties
 
    // Passing data annotations
    [MinLength(7, ErrorMessage = "Password Min Length is 7")]
    public string Password { get; set; }

}

And for the data annotations validation to work, don't forget that you need to have the DataAnnotationsValidator component inside the EditForm

<EditForm Model="@ModelValue">
    <DataAnnotationsValidator />

    @* rest of components *@
</EditForm>

Upvotes: 1

Related Questions