웹 앱에 React 입력 양식 마스크 및 유효성 검사 기능 추가

양식 요소는 웹사이트에서 사용자에게 요구하는 정보를 수집하는 일반적인 방법입니다. 일반적으로 요소, 확인란, 라디오 버튼 및 사용자가 입력한 정보를 제출하는 버튼으로 구성됩니다. 그러나 표준 요소는 사용자가 원하는 대로 입력할 수 있도록 하며 입력한 정보를 표준화하려는 경우 해당 기능을 구현하는 것은 개발자의 몫입니다.

그것이 InputMask가 들어오는 곳입니다. Wijmo의 React InputMask 컨트롤을 사용하면 개발자가 입력 필드에 대해 미리 정의된 형식인 마스크를 쉽게 구현할 수 있습니다. 이렇게 하면 사용자가 마스크에 입력할 수 있는 문자 수, 컨트롤에 표시되는 프롬프트 문자 및 컨트롤에서 사용자가 숫자, 문자 또는 둘 다를 입력할 수 있는지 여부를 제한할 수 있습니다.

이 문서에서는 다음 단계를 간략하게 설명합니다.
  • Creating a React Form
  • Implementing Wijmo’s React InputMask
  • Defining the Mask and Prompt Characters
  • Validating the User’s Information

  • 직접 프로젝트를 다운로드하려면 찾을 수 있습니다here.

    반응 양식 만들기

    The first thing that we’ll go over is creating the React form. Open up the App.js file and add the following markup for the form:

        <div class="form-control">
          <div class="form-header">
            <span>User Information</span>
          </div>
          <form class="form-body" onSubmit={submitForm}>
            <div class="form-footer">
              <button class="form-button" type="submit">Submit</button>
            </div>
          </form>
        </div>
    

    We’re using a form to aggregate the data from the user and React’s onSubmit markup to tie a method to the form to handle when the form gets submitted.

    The other thing that we’ll do in this section is add styles for the form. Open up the App.css file and add the following CSS:

        .form-control {
          position: absolute;
          width: 400px;
          height: 300px;
          z-index: 15;
          top: 50%;
          left: 50%;
          margin: -150px 0 0 -200px;
          border-radius: 15px;
          box-shadow: 1px 0 5px -2px rgb(90, 90, 90);
          text-align: center;
        }
    
        .form-header {
          height: 50px;
          width: 100%;
          line-height: 50px;
          border-top-left-radius: 15px;
          border-top-right-radius: 15px;
          background: rgb(100, 100, 252);
          font-weight: bold;
          font-size: larger;
          color: white;
        }
    
        .form-body {
          height: 100%;
          position: relative;
        }
    
        .form-footer {
          position: absolute;
          bottom: 75px;
          right: 2px;
          height: 50px;
          width: 100%
        }
    
        .form-button {
          float: right;
          margin-top: 10px;
          margin-right: 10px;
          height: 40px;
          width: 100px;
          border-radius: 10px;
          border: 1px solid black;
          background: rgb(100, 100, 252);
          color: white;
          font-size: 16px;
        }
    
        .form-button:hover {
          cursor: pointer;
          background: rgb(140, 140, 255);
        }
    

    The CSS we’ve just written will center the form on the page and style our header, footer, and button elements. Now, if you run the application, you should see the following:



    Wijmo의 React InputMask 구현

    Now that the form has been created, it's time to add our InputMasks. To use Wijmo, we will need to add the library to our project. Open up your command prompt, navigate to where your project is stored, and run the following:

        npm i @grapecity/wijmo.react.all
    

    Once NPM has installed all the files, open up the App.js file. Now that we’ve included Wijmo, we need to import the required Wijmo files to our product:

        import * as wjcCore from '@grapecity/wijmo';
        import * as wjcInput from '@grapecity/wijmo.react.input';
    

    The last thing to do is add Wijmo’s CSS library to our application. Open up the index.css file and add the following:

        @import '@grapecity/wijmo.styles/themes/wijmo.theme.material.css';
        body {
          box-sizing: boder-box;
          font-family: sans-serif;
        }
    

    With all of that done, we can now use Wijmo’s React InputMask. Go back to the App.js file and add the following markup inside of the

    element:
        <div className="form-element">
          <wjcInput.InputMask ref={name} id="name" placeholder="Name"></wjcInput.InputMask>
        </div>
        <div className="form-element">
          <wjcInput.InputMask ref={email} id="email" placeholder="Email"></wjcInput.InputMask>
        </div>
        <div className="form-element">
          <wjcInput.InputMask ref={phone} id="phone" placeholder="Phone Number"></wjcInput.InputMask>
        </div>
        <div className="form-element">
          <wjcInput.InputMask ref={social} id="social" placeholder="Social Security Number"></wjcInput.InputMask>
        </div>
    

    Here, we’re implementing 4 InputMasks; one for name, email, phone number, and social security number. We’re also setting a placeholder value for each mask, which will display inside the InputMask to let users know the expected input.

    The last thing that we’ll need to do is add some CSS to style the InputMasks:

        .form-element {
          text-align: center;
          margin-top: 15px;
          width: 100%;
        }
    

    Now, if you run the application, you should see the following:



    마스크 및 프롬프트 문자 정의

    Now that we’ve implemented the InputMasks, we’ll review how to set the mask and prompt characters for the controls. In this sample, we want to define a mask and prompt characters for the phone number and social security number inputs. We’re going to modify the markup for both of these InputMasks:

        <wjcInput.InputMask ref={phone} id="phone" placeholder="Phone Number" mask="000-000-0000" isRequired={false} value="" promptChar="#"></wjcInput.InputMask>
        <wjcInput.InputMask ref={social} id="social" placeholder="Social Security Number" mask="000-00-0000" isRequired={false} value="" promptChar="*"></wjcInput.InputMask>
    

    By using number characters in the mask property, we’re telling the InputMask that we only want to accept numbers when typing in the control and how many characters we require the user to input. Setting the prompChar property tells the control what character we want to show for the values that we still need input for. And finally, setting the isRequired and value properties will allow our placeholder to continue to display instead of defaulting to displaying the prompt characters. Now, if we run the application and begin typing in either the phone or social InputMask, we should see the following:



    보시다시피 이러한 InputMask 중 하나를 입력하면 컨트롤이 예상하는 나머지 문자에 대한 프롬프트 문자가 표시됩니다.

    사용자 정보 확인

    The last thing we’ll discuss in this article is how we can validate the user’s information. In the case of this form, we want them to enter information in the “Name” and “Email” InputMasks, and we want to make sure that the “Phone Number” and “Social Security Number” InputMasks have been completely filled out.

    We’ll first make sure that users know that the last 2 InputMasks need to be completely filled out. We’ll use Wijmo’s React InputMask valueChanged event to do that. Inside of the markup, add the event to the control:

        <wjcInput.InputMask ref={phone} id="phone" placeholder="Phone Number" mask="000-000-0000" isRequired={false} value="" promptChar="#" valueChanged={valueChanged}></wjcInput.InputMask>
        <wjcInput.InputMask ref={social} id="social" placeholder="Social Security Number" mask="000-00-0000" isRequired={false} value="" promptChar="*" valueChanged={valueChanged}></wjcInput.InputMask>
    

    Now, inside the App.js file, we’ll implement the following method:

        function valueChanged(ctrl) {
          wjcCore.toggleClass(ctrl.hostElement, 'state-invalid', !ctrl.maskFull);
        }
    

    This method checks if the maskFull property of the InputMask returns true; maskFull is a Boolean value that returns true if the user has entered the required number of characters by the mask and false if not. If it does not return true, then we add a CSS class named state-invalid to the control.

    We’ll add that CSS class to the App.css file:

        .state-invalid {
          color: red;
        }
    

    Now, as we type in the “Phone Number” or “Social Security Number” InputMasks, we’ll see the following:



    보시다시피 마스크가 완전히 채워지지 않은 경우 텍스트가 빨간색으로 표시됩니다.

    다음으로 사용자가 모든 InputMask를 채웠는지 확인하고 onSubmit() 메서드를 업데이트하여 양식을 제출할지 여부를 결정하는 메서드를 추가합니다.

        const name = createRef();
        const email = createRef();
        const phone = createRef();
        const social = createRef();
    
        function isFormComplete() {
          if(name.current.control.value !== '' && name.current.control.value !== '' && name.current.control.maskFull && name.current.control.maskFull) {
            return true;
          }
          return false;
        }
    
        function submitForm(event) {
          if(isFormComplete()) {
            alert('User Information:\nName: ' + name.current.control.value + 
            '\nEmail: ' + email.current.control.value + '\nPhone Number: ' + phone.current.control.value + 
            '\nSSN: ' + social.current.control.value)
          } else {
            event.preventDefault();
          }
        }
    

    이제 앱을 실행하고 모든 InputMask를 제대로 채우면 다음 경고가 표시됩니다.



    결론



    보시다시피 Wijmo의 React InputMask 컨트롤을 사용하여 양식을 쉽게 작성할 수 있습니다. 더 많은 정보를 원하시면 개발자를 위한 demos , documentationAPI references 을 참조하십시오. 완성된 응용 프로그램을 다운로드하려면 찾을 수 있습니다here.

    즐거운 코딩하세요!

    좋은 웹페이지 즐겨찾기